from kivy.logger import Logger

from amgineirc.viewModel.viewModel import ViewModel

class DefaultViewModel(ViewModel):
    """
    """
    def __init__(self, view, appdata):
        ViewModel.__init__(self, view)
        self._appdata = appdata
        self.view.vm_connect_button_handler = self.connect_button_handler

    def _get_unconnections(self):
        connections = self._appdata['client'].connections
        unconnections = {}
        itr = self._appdata['servers'].data.iteritems()
        for n, v in itr:
            if n not in connections:
                unconnections[n] = v
        return unconnections
                  
    def connect_button_handler(self, instance):
        from amgineirc.view.channels.defaultView import DefaultView, ConnectPopup
        if instance.text == DefaultView.connect_command:
            # open the server select button
            unconnections = self._get_unconnections()
            if len(unconnections) > 0:
                popup = ConnectPopup(self.server_on_press_handler)
                for n in unconnections:
                    popup.vm_add_domain(n,
                                        unconnections[n]['port'],
                                        unconnections[n]['secure'],
                                        unconnections[n]['nick'],
                                        unconnections[n]['nick_password'])
                popup.open()
            else:
                self.view.message_warn('You have connected to every one of your servers.')
        
    def handle_confirm_connect(self, truefalse, domain):
        if truefalse is True:
            # the user has confirmed wanting to connect to a server
            # the connection viewmodel will open and raise the server connection view
            # then it will have the server connection view model connect to the server
            self._appdata['connection_vm'].add_server_connection(domain)
            
    def server_on_press_handler(self, instance):
        key = instance.domain
        self.view.question_yes_no('Connect To A Server.',
                                  'Are you sure you want to connect to ' + key + '?',
                                  self.handle_confirm_connect,
                                  key)

    # private methods
